// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// f [author] rhyme_lph
// h [email]  rhymelph@gmail.com
// u [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/business_contact_entity.dart';
import 'package:finance_app/src/http_service/http_contact_service.dart';
import 'package:finance_app/src/mixin/check_plan_mixin.dart';
import 'package:finance_app/src/mixin/scroll_to_hide_mixin.dart';
import 'package:finance_app/src/provider/dashboard/contact/detail/contact_detail_person_provider.dart';
import 'package:finance_app/src/provider/dashboard/contact/detail/contact_detail_transaction_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/dashboard_add_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/judge_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:fluttercontactpicker/fluttercontactpicker.dart';

class BusinessContactDetailProvider extends BaseProvider<BusinessContactEntity>
    with ScrollToHideMixin, CheckPlanMixin {
  List<String> menuList = [
    S.current.view_profile,
    S.current.add_transaction,
    S.current.add_contact_person,
    S.current.generate_soa,
  ];

  int tabIndex = 0;

  List<String> tabList = [S.current.transactions, S.current.contact_person];

  int id;

  BusinessContactEntity contact;

  @override
  Future get dataFuture => null;

  void onSelectMenu(String value) async {
    switch (menuList.indexOf(value)) {
      case 0:
        _onNavViewProfile();
        break;
      case 1:
        _onNavAddTransaction();
        break;
      case 2:
        onAddContact();
        break;
      case 3:
        _onNavSOA();
        break;
    }
  }

  void onNavUnPaidInvoice() async {
    await Routes.navigateTo(RouterGenProviders.allTransactionsPage, params: {
      'type': 2,
      'initFilter': 'Unpaid',
      'contactId': contact.id,
    });
    loadDashBoard();
  }

  void onNavUnPaidBill() async {
    await Routes.navigateTo(RouterGenProviders.allTransactionsPage, params: {
      'type': 5,
      'initFilter': 'Unpaid Bill',
      'contactId': contact.id,
    });
    loadDashBoard();
  }

  void onNavCreditDebit() async {
    await Routes.navigateTo(RouterGenProviders.creditDebitPage, params: {
      'contactId': contact.id,
      // 'index': data.totalUnpaidCredit == 0 && data.totalUnpaidDebit > 0 ? 1 : 0,
    });
    loadDashBoard();
  }

  void onNavAdd() {
    if (isPlanExpired()) return;
    if (tabIndex == 0) {
      _onNavAddTransaction();
    } else {
      onAddContact();
    }
  }

  void onAddContact() {
    if (isPlanExpired()) return;
    obtainContext?.call((context) async {
      final result = await showImportContactJudgeBottomSheet(context);
      if (result == true) {
        bool isSuccess;
        if (!(await FlutterContactPicker.hasPermission())) {
          isSuccess = await FlutterContactPicker.requestPermission();
        } else {
          isSuccess = true;
        }
        if (isSuccess) {
          PhoneContact phoneContact =
              await FlutterContactPicker.pickPhoneContact();
          if (phoneContact != null) {
            final phoneNumber = phoneContact.phoneNumber;
            final name = phoneContact.fullName;
            Routes.navigateTo(RouterGenProviders.newContactPersonPage, params: {
              'name': name,
              'phoneNumber': phoneNumber?.number,
              'id': id,
            });
          }
        }
      } else {
        Routes.navigateTo(RouterGenProviders.newContactPersonPage, params: {
          'id': id,
        });
      }
    });
  }

  @override
  List<BaseProvider> registerChildProviders() {
    return [
      ContactDetailPersonProvider(),
      ContactDetailTransactionProvider(),
    ];
  }

  void _onNavViewProfile() async {
    final result = await Routes.navigateTo(
        RouterGenProviders.businessContactProfilePage,
        params: {'data': contact});
    if (result != null && result is Map) {
      if (result['delete'] == true) {
        obtainContext?.call((context) {
          Navigator.of(context).pop(result);
        });
      }
    }
    if (result != null && result is BusinessContactEntity) {
      updateContact(result);
    }
  }

  void _onNavSOA() async {
    if (isPlanExpired()) return;
    Routes.navigateTo(RouterGenProviders.statementOfAccountPage,
        params: {'data': contact});
  }

  void _onNavAddTransaction() {
    if (isPlanExpired()) return;
    obtainContext?.call((context) async {
      await showDashboardAddBottomSheet(context);
      onRefreshTransaction();
      loadDashBoard();
    });
  }

  void onHandleTabIndex(int index) {
    tabIndex = index;
  }

  void updateContact(BusinessContactEntity entity) {
    contact.fromJson(entity.toJson());
    update();
  }

  Future<void> loadDashBoard() async {
    await post(HttpContactService.showContact(id),
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      data = getEntityFromResult<BusinessContactEntity>(result);
      updateContact(data);
    });
  }

  void onRefreshTransaction() {
    getChildProvider<ContactDetailTransactionProvider>().onRefresh();
  }

  @override
  void initState() {
    super.initState();
    loadDashBoard();
  }
}
